from attributes.models import *
from django.contrib.contenttypes.models import ContentType

class AttributeDescriptor(object):
    proxy = None

    def __get__(self, instance, owner):
        if not self.proxy:
            self.proxy = AttributeProxy(instance)

        return self.proxy

class AttributeProxy(object):
    def __init__(self, instance):
        self.__dict__['instance'] = instance
        self.__dict__['content_type'] = ContentType.objects.get_for_model(self.instance)

    def __getitem__(self, name):
        attr = Attribute.objects.get(
            content_type=self.__dict__['content_type'],
            object_id=self.__dict__['instance'].pk,
            key=name)
        return getattr(attr, attr.type)

    def __setitem__(self, name, value):
        try:
            obj = self.__getitem__(name)
        except:
            obj = model_for_type(type(value))()
            obj.content_object = self.__dict__['instance']
            obj.key = name

        obj.value = value
        obj.save()
